import { deliveryTimeRule, moduleTypeRule, objectAny, queryWhereRule } from "../options/base";
import { mySchoolStore } from "../store";
import { buildOrderList } from "./orderHelper";
import { getMoment } from "./time";
import { showModal, showToast } from "./utils";

const db = uniCloud.database()

const orderManage = uniCloud.importObject(`admin-order-manage`, {customUI: true});
const publicManage=uniCloud.importObject(`admin-public-manage`,{customUI: true})
const clientUserManage=uniCloud.importObject(`client-user-manage`,{customUI: true})

export async function getMySelf(): Promise<{
    _id: string
}> {
    const { uid, ...others } = uniCloud.getCurrentUserInfo()
    if (uid !== null) {
        return {
            _id: uid,
            ...others
        };
    } else {
        console.log(`用户获取错误`);
    }
    return {
        _id: ``
    }
}

export type addressRule={
    is_default:boolean;
    address:string;
    moblie:string;
    name:string;
    school_id:string;
    user_id:string;
    _id:string
}
export async function getUserAddressList(
    schoolId:string,
    whereId?:string,
    getDefault?:boolean
):Promise<{
    errCode:0;
    myErrCode:10000|10001|0;
    errMsg?:string;
    data?:Array<addressRule>
}>{
    try {
        const { _id: userId } = await getMySelf()

        const {myErrCode,errMsg,data}= await clientUserManage.getUserAddressList(schoolId,whereId,getDefault)
        if(myErrCode!==0){
            showModal({
                title:`异常提示`,
                content:errMsg,
                showCancel:false
            })
            return {
                errCode: 0,
                myErrCode: 10000,
                data:[]
            }
        }
        const addressList=data.map((it:objectAny)=>{
            return {...it,school_id:schoolId,user_id:userId}
        })
        return {
            errCode: 0,
            myErrCode: 0,
            data:addressList
        }
    } catch (error) {
        console.error(error)
		return {
			errCode: 0,
			myErrCode: 10001,
			errMsg: '系统繁忙请稍后再试'
		}
    }
}

export async function getYiZhanAddressList(): Promise<Array<objectAny>> {
    const state = mySchoolStore();

    const { result: { data } } = await db
        .collection(`admin-yizhan-address`)
        .where(`school_id=="${state.mySchool._id}"`)
        .get();

    return data
}

/**
 * 目前仅用于查询 跑腿代取模块下的列表数据
 * @param {string} orderCode - 订单编号 
 * @param {moduleTypeRule} moduleName - 查询的模块
 * @param {queryWhereRule} queryWhere - 查询的条件
 * @returns 
 */
export async function baseGetOrderList(
    moduleName:moduleTypeRule,
    queryWhere: queryWhereRule
): Promise<objectAny> {
    const schoolStore = mySchoolStore();
    // 赋值本地的所属学校ID
    queryWhere.schoolId=schoolStore.mySchool._id;

    try {
        const {
            myErrCode,
            errMsg,
            data: serverData
        }=await orderManage.getOrderList(queryWhere);
        if (myErrCode !== 0) {
            await showModal({
                title: `异常提示`,
                content: errMsg,
                showCancel: false
            })
            return {}
        }

        const {  affectedDocs,  data }=serverData

        if (affectedDocs === 0) {
            return {}
        }

        const results:{
            [keyName:string]:objectAny
        } = buildOrderList(data,moduleName);

        return results;
    } catch (error) {
        console.log(`xxxxxx=>  baseGetOrderList 获取订单列表数据异常，异常信息如下： <=xxxxxx`)
        console.error(error)
    }
    return {}
}

export function cancelOrder(
    orderId: string,
    prompt: boolean | undefined = false
) {
    const schoolStore = mySchoolStore();

    if (prompt) {
        uni.showLoading({ title: `正在加载` })
    }


}

export async function changeOrderStatus(
    tableName:'admin-order-list'|'food-order-list',
    orderId: string,
    update: {
        order_status?:number;
        rider_order_status?:number
    },
    prompt: boolean | undefined = false
) {
    const schoolStore = mySchoolStore();

    if (prompt) {
        uni.showLoading({ title: `正在处理` })
    }
    const {
        errCode,
        errMsg,
        data: {
            affectedDocs
        }
    } = await publicManage.publicChangeOrderStatus(tableName,orderId, schoolStore.mySchool._id, update);

    if (prompt) {
        uni.hideLoading();
    }

    if (errCode !== 0) {
        await showModal({
            title: `异常提示`,
            content: errMsg,
            showCancel: true
        })
        return false
    }

    return affectedDocs > 0

}

export async function getOrderDetails(
    orderId: string,
    moduleName:moduleTypeRule,
    prompt: boolean | undefined = false
): Promise<objectAny> {
    const schoolStore = mySchoolStore();

    if (prompt) {
        uni.showLoading({ title: `正在加载` })
    }
    const {
        errCode,
        errMsg,
        data: {
            affectedDocs,
            data,
            serverNowTime
        }
    } = await orderManage.getOrderDetails(orderId, schoolStore.mySchool._id);

    if (prompt) {
        uni.hideLoading();
    }

    if (errCode !== 0) {
        await showModal({
            title: `错误提示`,
            content: errMsg,
            showCancel: true
        })
    }

    if (affectedDocs === 0) {
        return {}
    }

    const orderObject = buildOrderList(data,moduleName);
    return {
        ...Object.values(orderObject)[0],
        serverNowTime
    }
}

export async function getDeliveryTimeList(
    type:`runErrands`|`takeout`,
    prompt: boolean | undefined = false
):Promise<{
    list:deliveryTimeRule;
    nowTime:number;
    type:`runErrands`|`takeout`
}>{
    const schoolStore = mySchoolStore();
    if (prompt) {
        uni.showLoading({ title: `正在获取` ,mask:true})
    }
    try {
        const {data,myErrCode,errMsg} =await publicManage.createTimeSelectList(type,schoolStore.mySchool._id);
        if (prompt) { uni.hideLoading(); }

        if(myErrCode!==0){
            showModal({
                title:`异常提示`,
                content:errMsg,
                showCancel:false
            })
            return {
                list:[],
                nowTime:0,
                type
            }
        }
        return {
            list:data.list,
            nowTime:data.nowTime,
            type
        }
    } catch (error) {
        if (prompt) { uni.hideLoading(); }

        console.error(`xxxxxx=> 调用 getDeliveryTimeList 错误，错误信息如下： <=xxxxxx`)
        console.error(error)
        showModal({
            title:`异常提示`,
            content:`访问过于火爆，请稍后再试`,
            showCancel:false
        }) 
    }

    return {
        list:[],
        nowTime:0,
        type
    }
}

export async function assertTokenIsValid():Promise<boolean>{
    try {
        const {data,myErrCode,errMsg} =await clientUserManage.assertTokenIsValid();
        return data.valid
    } catch (error) {
        console.error(`xxxxxx=> 调用 assertTokenIsValid 校验异常，异常信息如下： <=xxxxxx`)
        console.error(error)
        await showModal({
            title:`异常提示`,
            content:`访问过于火爆，点击重试`,
            showCancel:false
        })
        return assertTokenIsValid();
    }
}